<!--
 * @Date: 2023-03-04 15:26:32
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-04-09 21:46:42
 * @FilePath: \A19\frontend\src\components\Lv3_exam.vue
-->
<!--
 * @Date: 2023-03-04 15:26:32
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-10 19:32:00
 * @FilePath: \A19\frontend\src\components\Lv3_exam.vue
-->
<template>
  <div id="Lv3_exam" class="list-container">
  <div class="head">
    {{ examOrHomework ===  'exam'?'考试':'作业' }}
    <div>
      <ElButton plain type="primary" v-if="poss" style="margin:10px;float:right;" @click="createExOrHo">创建{{ examOrHomework === 'exam'?'考试':'作业'}}</ElButton>
      <!-- <ElButton plain v-if="poss" style="margin:10px;float:right;" @click="exportExcel">数据导出</ElButton> -->
      <Transfer :getSelected="getSelected" :poss="poss" :datas="tableData"/>
    </div>
  </div>
    <!-- <div id="navi">
      <div id="all" class="navi"><el-link>考试</el-link></div>
      <div id="inProgress" class="navi"><el-link>进行中进行中</el-link></div>
      <div id="finish" class="navi"><el-link>已结束</el-link></div>
      <el-input placeholder="搜索" :suffix-icon="Search" />
    </div> -->
    <div style="height: calc(100% - 60px);">
      <el-table :data="filterTableData" style="width: 100%;height:calc(100% - 60px);">
        <el-table-column fixed  prop="name" label="考试名称"  sortable>
          <template #header>
            <el-input style="width: 200px;" v-model="search" size="default"  placeholder="搜索" />
            <!-- 考试名称 -->
          </template>
        </el-table-column>

        <el-table-column prop="startTime" label="开始时间" sortable>
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-icon><timer /></el-icon>
              <span style="margin-left: 10px">{{ (scope.row.startTime as Date).format('yyyy-MM-dd hh:mm:ss') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" sortable>
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-icon><timer /></el-icon>
              <span style="margin-left: 10px">{{ (scope.row.endTime as Date).format('yyyy-MM-dd hh:mm:ss') }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="member" label="进入人数/总人数" width="200" /> -->
        <el-table-column prop="status" label="考试状态" >
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px" :style="{
                color:(() =>{ 
                  if(scope.row.currentStatus === '未开始') return '#909399'
                  else if(scope.row.currentStatus === '已结束') return '#F56C6C'
                  else return '#67C23A'
                })()
              }">{{ scope.row.currentStatus }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :width="100">
          
          <template #default="scope" v-if="poss">
            <el-button v-if="scope.row.currentStatus === '进行中'" @click="watchOrJudge(scope.row._id)" link type="primary" size="small">{{ examOrHomework === 'exam'?'监考':'批阅' }}</el-button>
            <el-button v-if="scope.row.currentStatus === '未开始'" @click="editExOrHo(scope.row._id)" link type="primary" size="small">编辑</el-button>
            <el-button v-if="scope.row.currentStatus === '已结束'" @click="judgeExOrHo(scope.row._id)" link type="primary" size="small">批阅</el-button>
            <!-- <el-button link type="primary" size="small">监考</el-button> -->
          </template>
          <template #default="scope" v-else>
            <el-button v-if="scope.row.currentStatus === '进行中' && !isDoneTest(scope.row._id)" @click="testOrHomework(scope.row._id)" link type="primary" size="small">{{ examOrHomework ===  'exam'?'进入考试':'开始答题' }}</el-button>
            <ElButton v-if="scope.row.currentStatus === '进行中' && isDoneTest(scope.row._id)" :disabled="true"  link type="primary" size="small">已提交</ElButton>
            <el-button v-if="scope.row.currentStatus === '未开始'" disabled link type="primary" size="small">{{ examOrHomework ===  'exam'?'进入考试':'开始答题' }}</el-button>
            <el-button v-if="scope.row.currentStatus === '已结束'" @click="checkPaper(scope.row._id)" link type="primary" size="small">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
   
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed, inject, Ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useClientStore } from '../pinia/stores/client';
import { tests } from '../shared/types/tests';
import { useRoute, useRouter } from 'vue-router';
import { studentAnswer } from "@/shared/types/Answer";
import { Excel } from '../utils/excel';
import { courses } from '../shared/types/courses';

const courseInfo = inject<Ref<courses>>('courseInfo')

const store = useClientStore()
const {currentCourseId,currentUser} = storeToRefs(store)
const poss = computed(()=>{
    return currentUser.value.role === 'teacher'
})
const route = useRoute()
const router = useRouter()
const examOrHomework = ref<'exam' | 'homework'>(route.name as 'exam' | 'homework')
const courseId = route.params.courseId as string


const tableData = ref(new Array<thetests>);
const filterTableData = computed(() =>
tableData.value.filter(
  (data) =>
    !search.value ||
    data.name.toLowerCase().includes(search.value.toLowerCase())
  )
)
const doneTestOrHomework = ref(new Array<{
  _id: string
  student: string
  test: string
  submitTime: Date
  answers: Array<studentAnswer>
  score:number
  studentInfo: {
    _id: string;
    name: string;
    password?: string;
    role: string;
    email: string;
    school: string;
    number: string;
    gender: number;
    portrait: string;
  }[];
}>())
const isDoneTest = (testId:string) =>{
  // console.log(testId);
  const theTest = doneTestOrHomework.value.find(paper => paper.test === testId)
  // console.log(theTest);
  if(theTest){
    return true
  }
  return false
}

const statusFormer = (test:tests):thetests=>{
  const start = test.startTime
  const end = test.endTime
  let status = ''
  let color = ''
  if(new Date < start){
    color = '#909399'
    return {
      ...test,
      currentStatus:'未开始'
    }
  }
  else if(new Date > end){
    color = '#F56C6C'
    return {
      ...test,
      currentStatus:'已结束'
    }
  }
  else{
    color = '#67C23A'
    return {
      ...test,
      currentStatus:'进行中'
    }
  }
}
const createExOrHo = () =>{
  if(examOrHomework.value === 'exam'){
    router.push({name:'createTest',params:{courseId:route.params.courseId}})
  }
  else{
    router.push({name:'createHomework',params:{courseId:route.params.courseId}})
  }
  
}
const editExOrHo = (testId:string) =>{
  if(examOrHomework.value === 'exam'){
    router.push({name:'editTest',params:{testId}})
  }
  else{
    router.push({name:'editHomework',params:{testId}})
  }
}
const testOrHomework = (testId:string) =>{
  if(examOrHomework.value === 'exam'){
    router.push({name:'testDemo',params:{testId}})
  }
  else{
    router.push({name:'homeworkDemo',params:{testId}})
  }
}
const judgeExOrHo = (testId:string) =>{
  if(examOrHomework.value === 'exam'){
    router.push({name:'judge',params:{testId}})
  }
  else{
    router.push({name:'judgeHomework',params:{testId}})
    
  }
}
const watchOrJudge = (testId:string) =>{
  if(examOrHomework.value === 'exam'){
    router.push({name:'watcher',params:{testId}})
  }
  else{
    router.push({name:'judgeHomework',params:{testId}})
  }
 
}
const checkPaper = (testId:string) =>{
  if(examOrHomework.value === 'exam'){
    router.push({
      name:'checkTest',
      params:{
        testId
      }
    })
  }
  else{
    router.push({
      name:'checkHomework',
      params:{
        testId
      }
    })
  }
}
const search = ref('')

const getSelected = (selectedList:string[]) =>{
  exportExcel(selectedList)
}
const exportExcel = async (selectedList:string[]) =>{
  loadingInstance = ElLoading.service({
    target:'#app'
  })
  if(examOrHomework.value === 'homework'){
    const ret = await store.client.callApi('Get/GetAllHWInfo',{
      course:courseId,
      requiredHomework:selectedList
    })
    if(ret.isSucc){
      const data = {
        info:ret.res.info,
        students:ret.res.students.map((student,index,arr) =>{
          const scores = ret.res.info.map(test =>{
            const s = test.userHomework.find(h => h.student === student._id)
            return s?s.score:0
          })
          // Reflect.deleteProperty(student,'_id')
          student._id = (index + 1).toString()
          return [...Object.values(student),...scores]
        })
      }

      // console.log(data);
      Excel.exprotExcel((courseInfo?.value.name || '课程') + '作业',data,loadingInstance)
    }
  }
  else{
    const ret = await store.client.callApi('Get/GetAllTInfo',{
      course:courseId,
      requiredTest:selectedList
    })
    if(ret.isSucc){
      console.log(ret.res);
      const data = {
        info:ret.res.info,
        students:ret.res.students.map((student,index,arr) =>{
          const scores = ret.res.info.map(test =>{
            const s = test.userTests.find(h => h.student === student._id)
            return s?s.score:0
          })
          // Reflect.deleteProperty(student,'_id')
          student._id = (index + 1).toString()
          return [...Object.values(student),...scores]
        })
      }
      // console.log(data);
      Excel.exprotExcel((courseInfo?.value.name|| '课程') + '考试',data,loadingInstance)
    }
  }
}

let loadingInstance:any
onMounted(async () =>{
  loadingInstance = ElLoading.service({
    target:'#app'
  })
  if(!courseId) {
    ElMessage.error('不存在')
    loadingInstance.close()
    router.back()
    return
  }
  currentCourseId.value = courseId
  
  console.log(examOrHomework);
  const ret = await store.client.callApi('Get/GetCourseTest',{
    course:route.params.courseId as string,
    examOrHomework:examOrHomework.value
  }) 
  if(ret.isSucc){
    if(poss.value){
      ret.res.tests.forEach(test => {
        if(test.status ==='published') {
          tableData.value.push(statusFormer(test))
        }
      })
    }
    else{
      ret.res.tests.forEach(test => {
        if(test.status ==='published') {
          tableData.value.push(statusFormer(test))
        }
      })
    }
  }

  const ret2 = await store.client.callApi('Get/GetUserTest',{
    examOrHomework:examOrHomework.value,
  })
  if(ret2.isSucc){
    doneTestOrHomework.value = ret2.res.tests
  }
  loadingInstance.close()
  
})
interface thetests extends tests{
  currentStatus:'进行中' | '未开始' | '已结束'
}
</script>

<style lang="less" scoped>
* {
  // padding: 0;
  // margin: 0;
}

#Lv3_exam {
  width: 100%;
  // height: 100%;
  overflow: auto;
}

#navi {
  width: 100vw;
  position: relative;
  height: 5vh;
  background-color: rgb(215, 197, 238);
  color: #fff;

  .navi {
    width: 100px;
    background-color: rgb(215, 197, 238);
    text-align: center;
    line-height: 5vh;
    color: #fff;
  }
  display: flex;
  .el-input {
    position: relative;
    top: 6px;
    width: 200px;
    height: 25px;
    left: 830px;
  }
}

table {
  width: 88vw;
  tr {
    height: 40px;
    background-color: aqua;
    text-align: center;
    line-height: 40px;

    td {
      border: 1px solid #000000;
    }
  }
}
</style>
